import { defineComponent, watch, shallowReactive, ref } from 'vue'
import * as echarts from 'echarts'

// 声明类型
const PropsType = {
  tips: {
    type: Number,
    default: 50,
    require: true
  },
  date: {
    type: Array,
    default: [],
    require: false
  },
  unit:{
    type: String,
    default: '',
    require: false
  },
  dataLast: {
    type: Array,
    default: [],
    require: false
  },
  dataNow: {
    type: Array,
    default: [],
    require: false
  },
  colorObj: {
    type: Object,
    default: () => ({
      textStyle: "#fff",
      series: {
        color: ["#00bcd44a", "transparent"],
        dataColor: {
          normal: "#03a9f4",
          shadowColor: "#97e2f5"
        }
      }
    })
  }
} as const

// 定义主体
export default defineComponent({
  props: PropsType,
  setup(props) {
    const chartRef = ref()
    // 配置项
    let options = shallowReactive({tooltip:null, xAxis: null, series: null, color: null, yAxis: null, legend: null, dataZoom: null })

    watch(
      () => props,
      (val: any) => {
        options = {
          legend: {
            data: ['去年', '今年',]
          },  
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              label: {
                backgroundColor: '#6a7985'
              }
            }
          },

          xAxis: {
            type: 'category',
            data: props.date,
            axisLabel: {
              // interval:5,
              // rotate:40,
              formatter: function( params ) {
                return params.split(' ')[0] // 由于可能有多个series，因此params[0].name和.data表示第一个series的该坐标点 xAxis值和yAxis值
              }
            }
            
          },
          color: ['rgba(245, 191, 49, 1)', 'rgba(49, 219, 245, 1)', 'rgba(49, 127, 245, 1)'],
          yAxis: {
            type: 'value',
            name:props.unit
          },
          series: [
            {
              data: props.dataLast,
              type: 'line',
              name: '去年'
            },
            {
              data: props.dataNow,
              type: 'line',
              name: '今年'
            },

          ],
          dataZoom: [
            {
              show: true,
              realtime: true,
              start: 65,
              end: 85
            },
            {
              type: 'inside',
              realtime: true,
              start: 65,
              end: 85
            }
          ],

        }
        // 手动触发更新
        if (chartRef.value) {
          // 通过初始化参数打入数据
          chartRef.value.initChart(options)
        }
      },
      {
        immediate: true,
        deep: true
      }
    )

    return () => {
      const height = "310px"
      const width = "830px"

      return <div>
        <echart ref={chartRef} class="mr-auto" options={options} height={height} width={width} />
      </div>
    }
  }
})

